﻿/* 
 * 
 * Copyright 2013 Bendsoft. All rights reserved.
 * http://www.bendsoft.com
 * 
 * This code is distributed under the New BSD License (BSD).
 * 
 * @package     Camelot SharePoint Integration Plugins Library
 * @codeplex    http://camelottoolkit.codeplex.com
 * @license     New BSD License (BSD)
 * 
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Camelot.SharePointIntegration.IntegrationService;
using Camelot.SharePointIntegration.IntegrationService.Entities;
using Camelot.SharePointIntegration.Client;

namespace Camelot.SharePointIntegration.Plugins
{
    public class CamelotXmlToDisk : ListDataPlugin
    {
        protected override ServicePluginResult ProcessData(Task task, ListData data, List<Parameter> parameters)
        {
            string folder = (from p in parameters where p.Name.ToLower() == "folder" select p.Value).FirstOrDefault();

            if (String.IsNullOrEmpty(folder))
                return new IntegrationService.ServicePluginResult() { Message = "Parameter null or empty: folder" };

            if (!folder.EndsWith("\\"))
                folder += "\\";

            if (!Directory.Exists(folder))
                return new IntegrationService.ServicePluginResult() { Message = "The folder does not exist" };

            var xml = CamelotXml.CreateXml(data);

            System.IO.File.WriteAllText(folder + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xml", xml, Encoding.UTF8);
            return new IntegrationService.ServicePluginResult() { Success = true };
        }
    }
}
